package com.xinwei.leetcode.数组;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

// https://leetcode-cn.com/problems/single-number/
public class _136_只出现一次的数字 {
    public int singleNumber(int[] nums) {
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (!set.contains(nums[i])) {
                // 集合中第一次出现这个数
                set.add(nums[i]);
            } else {
                // 集合中出现过这个数
                set.remove(nums[i]);
            }
        }
        int onlyOne = 0;
        for (Integer integer : set) {
            onlyOne = integer;
        }
        return onlyOne;
    }

    public static int singleNumber1(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            Integer count = map.get(nums[i]);
            count = count == null ? 1 : ++count;
            map.put(nums[i], count);
        }
        for (Integer integer : map.keySet()) {
            if (map.get(integer) == 1) {
                return integer;
            }
        }
        return -1;
    }

}
